import axios from "axios";
// qs组件
import qs from "qs";

import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// 定义请求接口
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
// 设置跨域请求中可附带cookie参数
axios.defaults.withCredentials = true;
// 设置统一请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";

// request interceptor
axios.interceptors.request.use(
  config => {
    // do something before request is sent

    // 在请求前处理事项
    config.data = qs.stringify(config.data);

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
axios.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if ((res.code && res.code !== 20000) || (res.status && res.status !== 1)) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm(
          "You have been logged out, you can cancel to stay on this page, or log in again",
          "Confirm logout",
          {
            confirmButtonText: "Re-Login",
            cancelButtonText: "Cancel",
            type: "warning"
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

/**
 * @method get-自主封装get请求
 *
 * @param {String} url - 请求路径
 * @param {Object} params={} 请求参数
 *
 * @example
 * get('xxxxx', {a: 1})
 */
export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then(response => {
        resolve(response);
      })
      .catch(error => {
        reject(error);
      });
  });
};
/**
 * @method post-自主封装post请求
 *
 * @param {String} url - 请求路径
 * @param {Object} data={} 请求参数
 *
 * @example
 * post('xxxxx', {a: 1})
 */
export const post = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "POST",
      url: url,
      data: data
    }).then(
      response => {
        resolve(response);
      },
      error => {
        reject(error);
      }
    );
  });
};
/**
 * @method listData-自主封装列表数据整合
 *
 * @param {String} url - 请求路径
 * @param {Object} vueExample 当前实例
 *
 * @example
 * listData('xxxxx', this)
 */
export const listData = (url, vueExample) => {
  vueExample.loading = true;

  let filterParams = {};

  // 去除空值的对象
  for (let key in vueExample.filterParams) {
    if (vueExample.filterParams[key] || vueExample.filterParams[key] === 0) {
      filterParams[key] = vueExample.filterParams[key];
    }
  }

  // 执行请求
  return get(url, {
    pageIndex: 1, // 默认请求第一页
    ...filterParams,
    ...vueExample.filterDefaultParams
  })
    .then(data => {
      if (data.status) {
        // 列表数据
        vueExample.list = data.data;
      } else {
        // 列表数据
        vueExample.list = [];
      }
      // 分页数据
      vueExample.pageData = {
        total: data.pageCount || 0,
        pageSize: data.pageSize || 15,
        pageIndex: vueExample.filterParams.pageIndex || 1
      };
    })
    .catch(() => {})
    .finally(() => {
      vueExample.loading = false;
    });
};
